package com.rundow.common.sdk.listener;

import com.rundow.center.manager.service.EventService;
import com.rundow.common.base.constant.CacheConstant;
import com.rundow.common.base.constant.CommonConstant;
import com.rundow.common.base.model.event.DeviceEvent;
import com.rundow.common.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.ThreadPoolExecutor;

@Slf4j
@Component
public class DeviceEventListener {


    @Resource
    private RedisUtil redisUtil;
    @Resource
    private EventService eventService;
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Async
    @EventListener
    public void deviceEventReceive(DeviceEvent deviceEvent) {
        if (null == deviceEvent || null == deviceEvent.getDeviceId()) {
            log.error("Invalid device event: {}", deviceEvent);
            return;
        }
        log.debug("Device {} event, From: {}, Event: {}", deviceEvent.getType(), deviceEvent.getDeviceId(), deviceEvent);

        switch (deviceEvent.getType()) {
            // Save device heartbeat to Redis
            case CommonConstant.Device.Event.HEARTBEAT:
                redisUtil.setKey(
                        CacheConstant.Prefix.DEVICE_STATUS_KEY_PREFIX + deviceEvent.getDeviceId(),
                        deviceEvent.getContent(),
                        deviceEvent.getTimeOut(),
                        deviceEvent.getTimeUnit()
                );
                break;
            case CommonConstant.Device.Event.ERROR:

            case CommonConstant.Device.Event.OVER_UPPER_LIMIT:
                //TODO 去重
                threadPoolExecutor.execute(() -> eventService.addDeviceEvent(deviceEvent));
            case CommonConstant.Device.Event.OVER_LOWER_LIMIT:
                //TODO 去重
                threadPoolExecutor.execute(() -> eventService.addDeviceEvent(deviceEvent));
                break;
            default:
                log.error("Invalid event type, {}", deviceEvent.getType());
                break;
        }

    }


}
